import 'dart:convert';
import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:schoolassets/%E7%99%BB%E5%BD%95/Login.dart';
import 'package:shared_preferences/shared_preferences.dart';


import 'LoadToast.dart';
import 'Logger.dart';
import 'ShowToast.dart';
var ApiUrl;
String TestApiUrl = "";
Dio dio = new Dio();

class requestUrl {
  CommenRequest(String Url, String Method, var RequsetData,
      String LoadingContent, context, IsLoading,String contentType) async {
    try {
      var ResponseData;
      String Token="";
      var Oid;
      // 获取本地token
      final SharedPreferences sharedPreferences =
      await SharedPreferences.getInstance();
      try{

        Token = sharedPreferences.getString('Token')!;
      }catch(e){

      }
      // 获取本地ip地址
      ApiUrl = sharedPreferences.getString('ApiUrl');
      if (ApiUrl == null) {
        // 如果没有设置IP地址
        //默认地址为公网地址
        ApiUrl = "http://192.168.43.147:1090";
        //地址保存本地
        sharedPreferences.setString("ApiUrl",ApiUrl);
      }
      if (IsLoading) {
        // 加载框
        LoadToast().LoadingToast(LoadingContent, context);
      }

      print("参数:${json.encode(RequsetData)}");
      print("请求地址$Url");

      if(!contentType.isEmpty){
        //  构造contenttype
        dio.options.contentType = contentType;
      }
      if(!Token.isEmpty){
        // 构造请求头Image
        dio.options.headers['Cookie'] ="Token=$Token";
      }
      // dio.options.connectTimeout=5000;
      // dio.options.receiveTimeout=3000;
      dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
        return handler.next(options);
      }, onResponse: (response, handler) {
        if (response != null) {
          // Log().logger.e("信息:${response.statusCode}");
          return handler.next(response);
        } else {
          return null;
        }
      }, onError: (DioError e, handler) async {
        if (e.response != null) {
            Log().logger.e("错误信息:${e.response!.statusCode}");
          if (e.response!.statusCode == 401) {//catch the 401 here
            //    弹窗提示重新登陆
            //弹出提示框
            showDialog<Null>(
              context: context,
              barrierDismissible: false,
              builder: (BuildContext contextInsideDialog) {
                return new AlertDialog(
                  title: new Text('登录已过期'),
                  content: new SingleChildScrollView(
                    child: new ListBody(
                      children: <Widget>[
                        new Text('请点击确定重新登陆？'),
                      ],
                    ),
                  ),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text('确定'),
                      onPressed: () {
                        ///跳转到起始页并关闭所有页面
                        Navigator.of(contextInsideDialog).pop();
                        Navigator.push(context, MaterialPageRoute(builder: (context)=>Login()));
                      },
                    ),

                  ],
                );
              },
            ).then((val) {
            });
          }
          if(e.response!.statusCode == 404){
            ShowToast().MyToast("请求超时!");
            if (IsLoading) {
              LoadToast().CloseLoading();
              return;
            }
          }
        }
      }));

      if (Method == "post") {
        ResponseData = await dio.post(ApiUrl + Url, data: RequsetData);
      } else {
        // log("get2:${}");
        ResponseData =
        await dio.get(ApiUrl + Url, queryParameters: RequsetData);

      }
      if (ResponseData.statusCode == 200) {
        // 请求成功
        ResponseData = json.decode(ResponseData.toString());
        if (IsLoading) {
          LoadToast().CloseLoading();
        }
        log("数据返回:${json.encode(ResponseData)}");
        return ResponseData;
      }else{
        log("请求失败，状态码:${ResponseData.statusCode}");
        return "";
      }


    } catch (e) {
      print("异常信息:$e");
      if (IsLoading) {
        LoadToast().CloseLoading();
      }
      ShowToast().MyToast("系统异常");
    }
  }

///异步请求
  AsyncCommenRequest(String Url, String Method, var RequsetData,
      String LoadingContent, context, IsLoading,String contentType)   async {
    try {
      var ResponseData;
      String Token="";
      var Oid;
      // 获取本地token
      final SharedPreferences sharedPreferences =
      await SharedPreferences.getInstance();
      try{

        Token = sharedPreferences.getString('Token')!;
      }catch(e){

      }
      // 获取本地ip地址
      ApiUrl = sharedPreferences.getString('ApiUrl');
      if (ApiUrl == null) {
        // 如果没有设置IP地址
        //默认地址为公网地址
        ApiUrl = "http://192.168.43.147:1090";
        //地址保存本地
        sharedPreferences.setString("ApiUrl",ApiUrl);
      }
      if (IsLoading) {
        // 加载框
        LoadToast().LoadingToast(LoadingContent, context);
      }

      print("参数:${json.encode(RequsetData)}");
      print("请求地址$Url");

      if(!contentType.isEmpty){
        //  构造contenttype
        dio.options.contentType = contentType;
      }
      if(!Token.isEmpty){
        // 构造请求头
        dio.options.headers['Authorization'] =Token;
      }
      dio.options.connectTimeout=5000;
      dio.options.receiveTimeout=3000;
      dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) {
        return handler.next(options);
      }, onResponse: (response, handler) {
        if (response != null) {
          return handler.next(response);
        } else {
          return null;
        }
      }, onError: (DioError e, handler) async {
        if (e.response != null) {
          Log().logger.e("错误信息:${e.response!.statusCode}");
          if (e.response!.statusCode == 401) {//catch the 401 here
            //    弹窗提示重新登陆
            //弹出提示框
            showDialog<Null>(
              context: context,
              barrierDismissible: false,
              builder: (BuildContext contextInsideDialog) {
                return new AlertDialog(
                  title: new Text('登录已过期'),
                  content: new SingleChildScrollView(
                    child: new ListBody(
                      children: <Widget>[
                        new Text('请点击确定重新登陆？'),
                      ],
                    ),
                  ),
                  actions: <Widget>[
                    new FlatButton(
                      child: new Text('确定'),
                      onPressed: () {
                        ///跳转到起始页并关闭所有页面
                        Navigator.of(contextInsideDialog).pop();
                        Navigator.push(context, MaterialPageRoute(builder: (context)=>Login()));
                      },
                    ),

                  ],
                );
              },
            ).then((val) {
            });
          }
          if(e.response!.statusCode == 404){
            if (IsLoading) {
              LoadToast().CloseLoading();
              ShowToast().MyToast("请求超时!");
              return;
            }
          }
        }
      }));

      if (Method == "post") {
        ResponseData = await dio.post(ApiUrl + Url, data: RequsetData);
      } else {
        // log("get2:${}");
        ResponseData =
        await dio.get(ApiUrl + Url, queryParameters: RequsetData);

      }
      if (ResponseData.statusCode == 200) {
        // 请求成功
        ResponseData = json.decode(ResponseData.toString());
        if (IsLoading) {
          LoadToast().CloseLoading();
        }
        log("数据返回:$ResponseData");
        return ResponseData;
      }else{
        log("请求失败，状态码:${ResponseData.statusCode}");
        return "";
      }


    } catch (e) {
      print("异常信息:$e");
      if (IsLoading) {
        LoadToast().CloseLoading();
      }
      ShowToast().MyToast("系统异常");
    }
  }

}




